package com.iwunu.auth.helper;

import com.iwunu.auth.config.JwtConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

@Component
public class JwtTokenHelper {
	private final static Logger LOGGER = LoggerFactory.getLogger(JwtTokenHelper.class);
	
	private final static BASE64Decoder decoder = new BASE64Decoder();
	
	@Autowired
	private JwtConfig jwtConfig;
	
	public String read(HttpServletRequest request) throws UnsupportedEncodingException, IOException {
		LOGGER.debug("get jwt header key:{}", jwtConfig.getHeaderKey());
		String authorization = request.getHeader(jwtConfig.getHeaderKey());
		
		return read(authorization);
	}
	
	public String read(String authorization) throws UnsupportedEncodingException, IOException {
		if (authorization != null && authorization.startsWith(jwtConfig.getHeaderPrefix())) {
			String token = authorization.substring(jwtConfig.headerPrefixLength());
			String[] ss = token.split("\\.");
			if(ss.length==3) {
				return new String(Base64.getDecoder().decode(ss[1].getBytes()));
			}
		}
		return null;
	}

	public JwtConfig getJwtConfig() {
		return jwtConfig;
	}

	public void setJwtConfig(JwtConfig jwtConfig) {
		this.jwtConfig = jwtConfig;
	}
	
	
}
